/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.log.formoperate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yhao.infra.apilist.ValidationForm;
import yhao.infra.common.InfraCommonConstants;

/**
 * form操作日志记录工具
 * <p>这是日志记录的另一种实现，不同于#{@link yhao.infra.service.datasource.stat.LoggerUtil}自动生成的方式，
 * 这个方式把日志定义权交给了用户。
 * <p>
 * 	<appender name="formOperateAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
 * 		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 * 			<FileNamePattern>${log.base}/formOpe/formOpe.%d{yyyy-MM-dd}.log</FileNamePattern>
 * 			<MaxHistory>30</MaxHistory>
 * 		</rollingPolicy>
 * 		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
 * 			<pattern>#s_logger#%d{yyyy-MM-dd HH:mm:ss.SSS}%n%msg #e_logger#%n</pattern>
 * 		</encoder>
 * 	</appender>
 *
 * 	@author yoara
 */
public class LogUtil {
    private static Logger logger = LoggerFactory.getLogger(InfraCommonConstants.FORM_OPERATE_LOGGER);
    private static String HYPHEN = "-";
    private static String SPLIT = "#";
    public static void doLog(LogInfo info){
        if(info==null){
            return;
        }
        StringBuffer content = new StringBuffer();
        content.append("method:").append(nullToHyphen(info.getMethod())).append(SPLIT);
        content.append("desc:").append(nullToHyphen(info.getDesc())).append(SPLIT);
        content.append("form:").append(formToString(info.getForm())).append(SPLIT);
        content.append("result:").append(info.getResult());
        logger.info(content.toString());
    }

    private static String formToString(ValidationForm form) {
        if(form!=null){
            ObjectMapper mapper=new ObjectMapper();
            try {
                return mapper.writeValueAsString(form);
            } catch (JsonProcessingException e) {}
        }
        return "-";
    }

    private static String nullToHyphen(String method) {
        if(StringUtils.isBlank(method)){
            return HYPHEN;
        }
        return method;
    }
}
